from PySide2.QtWidgets import (
    QVBoxLayout,
    QLabel,
    QHBoxLayout,
    QPushButton,
    QDialog,
    QGridLayout,
    QTableWidget,
    QHeaderView,
    QWidget,
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage
import ast
from ..utils import Utils
from ..dlg_model_params import DlgModeResetCls
from ..custom_widget import LineEditFloat


class CGridLayout(QGridLayout):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAlignment(Qt.AlignTop)


# 数组追加按钮
class CustomCellAddButton(QWidget):
    def __init__(self, on_click, *args, **kwargs):
        super(CustomCellAddButton, self).__init__(*args, **kwargs)
        layout = QHBoxLayout()
        layout.setSpacing(5)
        layout.setContentsMargins(10, 0, 10, 0)

        self.widget = QPushButton("添加行")
        self.widget.clicked.connect(on_click)
        layout.addWidget(self.widget)
        self.setLayout(layout)
        # self.widget.setFixedHeight(getWidgetHeight())
        # self.widget.setStyleSheet("""
        #     QPushButton {
        #         width:100%;
        #         height:100%;
        #         margin:0;
        #     }
        # """)


class ListTable(QTableWidget):
    def __init__(self, parent=None):
        super(ListTable, self).__init__(parent)
        self.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.horizontalHeader().setHighlightSections(False)

    # 插入一行，可设置数据
    def addRow(self, rowData=""):
        row = self.rowCount()
        self.insertRow(row)
        for column in range(self.columnCount()):
            editLine = LineEditFloat()
            layout = QVBoxLayout()
            layout.setSpacing(5)
            layout.setContentsMargins(10, 0, 10, 0)
            layout.addWidget(editLine)
            cell_widget = QWidget()
            cell_widget.setLayout(layout)
            self.setCellWidget(row, column, cell_widget)
        self.fillRowData(row, rowData)
        return editLine

    # 末尾插入多行，并设置数据
    def addMulitRows(self, rowsData=[]):
        for rowData in rowsData:
            self.addRow(rowData=rowData)
        # row = self.rowCount()-1
        # self.setCellWidget(row, 0, self.__initAddBtnCellWidget())

    # 填充指定行数据
    def fillRowData(self, row, rowData):
        wrapWidget = self.cellWidget(row, 0)
        wrapLayout = wrapWidget.layout()
        editLine = wrapLayout.itemAt(0).widget()
        editLine.setValue(self.getRuleValueToStr(rowData))

    # def __initAddBtnCellWidget(self):
    #     return CustomCellAddButton(lambda *args: self.addRowHandle())

    def getDataList(self):
        data = []
        for row in range(self.rowCount()):
            wrapWidget = self.cellWidget(row, 0)
            wrapLayout = wrapWidget.layout()
            editLine = wrapLayout.itemAt(0).widget()
            value = editLine.getValue()
            if value is not None:
                data.append(editLine.getValue())
        return data

    def addRowHandle(self):
        self.delete_last_row()
        editLine = self.addRow()
        row = self.rowCount() - 1
        self.setCellWidget(row, 0, self.__initAddBtnCellWidget())
        self.scrollToBottom()
        # 设置最新行的widget 的焦点
        editLine.widget.setFocus()

    def delete_last_row(self):
        """删除最后一行"""
        row_count = self.rowCount()  # 获取当前表格的行数
        if row_count > 0:
            self.removeRow(row_count - 1)  # 删除最后一行
        else:
            print("表格为空，无法删除行")

    def getRuleValueToStr(self, value):
        return str(Utils.toFloat(value))


class StringedBarSize(DlgModeResetCls):
    update_signal = Signal(object)

    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        self.data = params.get("data")
        self.setWindowTitle("尺寸设置")
        self.resize(400, 400)
        self.layout = QVBoxLayout(self)

        self.table = ListTable()
        self.table.setRowCount(0)
        self.table.setColumnCount(1)
        self.table.setHorizontalHeaderLabels(
            [
                "尺寸各项赋值（数组）",
            ]
        )
        self.layout.addWidget(self.table)

        btnLayout = QHBoxLayout()
        # btnLayout.setContentsMargins(-1, 10, -1, -1)  # 左, 上, 右, 下
        btnLayout.setAlignment(Qt.AlignCenter)
        addBtn = QPushButton("新增")
        saveBtn = QPushButton("确定")
        cancelBtn = QPushButton("取消")
        btnLayout.addWidget(addBtn)
        btnLayout.addWidget(saveBtn)
        btnLayout.addWidget(cancelBtn)
        self.layout.addLayout(btnLayout)

        addBtn.clicked.connect(self.on_addBtn_clicked)
        saveBtn.clicked.connect(self.on_saveBtn_clicked)
        cancelBtn.clicked.connect(self.close)
        self.setLayout(self.layout)

        if self.data:
            try:
                array = ast.literal_eval(self.data)
                if isinstance(array, list):
                    self.table.addMulitRows(array)
            except (ValueError, SyntaxError) as e:
                print(f"解析错误: {e}")

    def on_addBtn_clicked(self):
        self.table.addRow()

    def on_saveBtn_clicked(self):
        data = self.table.getDataList()
        self.close()
        self.update_signal.emit(data)

    def updateUI(self, values):
        for k, v in values.items():
            if k in self.widgetDict:
                self.widgetDict[k].setValue(v)
